package com.xcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.xcm.cache.RedisCacheDao;
import com.xcm.config.CustomProperties;
import com.xcm.constant.ClientConstant;
import com.xcm.constant.ResponseConstant;
import com.xcm.exception.ControllerException;
import com.xcm.exception.ServiceException;
import com.xcm.model.JsonResponse;
import com.xcm.model.TbDeviceGroup;
import com.xcm.model.dto.DeviceGroupTreeListDTO;
import com.xcm.service.DeviceGroupService;
import com.xcm.util.GetUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/deviceGroup")
public class DeviceGroupController {
    private static Logger logger = LoggerFactory.getLogger(DeviceGroupController.class);
    @Autowired
    private DeviceGroupService deviceGroupService;
    @Autowired
    private RedisCacheDao redisCacheDao;
    @Autowired
    private CustomProperties customProperties;
    /**
     *  终端分组列表
     */
    @ResponseBody
    @RequestMapping(value = "/listDeviceGroup")
    public Object listDeviceGroup() {
        try {
            return deviceGroupService.listAllDeviceGroup();
        } catch (Exception e) {
            logger.error("DeviceGroupController saveDeviceGroup 终端分组列表失败：" + e.getMessage());
            return new ControllerException("终端分组列表失败");
        }
    }


    /**
     *  保存终端分组
     */
    @ResponseBody
    @RequestMapping(value = "/saveDeviceGroup")
    public Object saveDeviceGroup(TbDeviceGroup deviceGroup, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("DeviceGroupController saveDeviceGroup 保存终端分组失败：" + e.getMessage());
            return new ControllerException(e.getMessage());
        }
        if(user == null) {
            return new ControllerException("用户名为空，请联系管理员");
        }
        String message = "";
        String groupName = deviceGroup.getGroupName();
        String groupCode = deviceGroup.getGroupCode();
        if (StringUtils.isBlank(groupName)) {
            message = message + "分组名不能为空";
        } else if (StringUtils.isBlank(groupCode)) {
            message = message + "分组码不能为空";
        }
        if (message.length() > 0) {
            return new ControllerException(message);
        }
        try {
            deviceGroupService.saveDeviceGroup(deviceGroup, user, request);
        } catch (Exception e) {
            logger.error("DeviceGroupController saveDeviceGroup 保存终端分组失败：" + e.getMessage());
            return new ControllerException("保存终端分组失败");
        }
        return "保存终端分组成功";
    }

    /**
     *  更新终端分组
     */
    @ResponseBody
    @RequestMapping(value = "updateDeviceGroup")
    public Object updateDeviceGroup(TbDeviceGroup deviceGroup, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("DeviceGroupController updateDeviceGroup 更新终端分组失败：" + e.getMessage());
            return new ControllerException(e.getMessage());
        }
        if(user == null) {
            return new ControllerException("用户名为空，请联系管理员");
        }
        String message = "";
        Long groupId = deviceGroup.getDeviceGroupId();
        String groupName = deviceGroup.getGroupName();
        String groupCode = deviceGroup.getGroupCode();
        if(groupId == null) {
            message = message + "终端分组id不能为空";
        } else if (StringUtils.isBlank(groupName)) {
            message = message + "分组名不能为空";
        } else if (StringUtils.isBlank(groupCode)) {
            message = message + "分组码不能为空";
        }
        if (message.length() > 0) {
            return new ControllerException(message);
        }
        try {
            deviceGroupService.updateDeviceGroup(deviceGroup, user, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("DeviceGroupController updateDeviceGroup 更新终端分组失败：" + e.getMessage());
            return new ControllerException("更新终端分组失败");
        }
        return "更新终端分组成功";
    }

    /**
     *  删除终端分组
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDeviceGroup")
    public Object deleteDeviceGroup(Long deviceGroupId, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("DeviceGroupController deleteDeviceGroup 删除终端分组失败：" + e.getMessage());
            return new ControllerException(e.getMessage());
        }
        if(user == null) {
            return new ControllerException("用户名为空，请联系管理员");
        }
        if (deviceGroupId == null) {
            return new ControllerException("终端分组id不能为空");
        }
        try {
            //检查终端分组是否有子分组
            List<TbDeviceGroup> deviceChildGroupList = deviceGroupService.listDeviceGroupByParentId(deviceGroupId);
            if ( deviceChildGroupList.size() > 0 && !deviceChildGroupList.isEmpty()) {
                return new JsonResponse(ResponseConstant.CODE_FAIL,"删除终端分组失败,终端分组下有子分组");
            }
            deviceGroupService.deleteDeviceGroup(deviceGroupId, user, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("DeviceGroupController deleteDeviceGroup 删除终端分组失败：" + e.getMessage());
            return new ControllerException("删除终端分组失败");
        }
        return "删除终端分组成功";
    }

    /**
     * 生成分组树形列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listDeviceGroupTree")
    public Object deviceGroupTreeList() {
        Map<String,Object> data = new HashMap<String,Object>();
        try {
            //查询所有菜单
            List<DeviceGroupTreeListDTO> allMenu = deviceGroupService.listAllDeviceGroupTree();
            //根节点
            List<DeviceGroupTreeListDTO> rootMenu = new ArrayList<DeviceGroupTreeListDTO>();

            for (DeviceGroupTreeListDTO nav : allMenu) {
                //父节点为null的，为根节点。
                if(nav.getPid() == null || "".equals(nav.getPid())){
                    rootMenu.add(nav);
                }
            }
            //为根菜单设置子菜单，getClild是递归调用的
            for (DeviceGroupTreeListDTO nav : rootMenu) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<DeviceGroupTreeListDTO> childList = getChild(nav.getDeviceGroupId(), allMenu);
                //给根节点设置子节点
                nav.setChildren(childList);
            }

            /**
             * 自创一个最高节点叫“全部分组”
             * 它是所有根节点的父节点
             */
            DeviceGroupTreeListDTO specialMenu = new DeviceGroupTreeListDTO();
            specialMenu.setLabel("全部分组");
            specialMenu.setGroupCode("all_device");
            specialMenu.setOpen(true);
            specialMenu.setChildren(rootMenu);
            // 返回给页面的树形列表
            List<DeviceGroupTreeListDTO> treeMenu = new ArrayList<DeviceGroupTreeListDTO>();
            treeMenu.add(specialMenu);
            return treeMenu;
        } catch (Exception e) {
            logger.error("DeviceGroupController saveDeviceGroup 终端分组列表失败：" + e.getMessage());
            return new ControllerException("终端分组列表失败");
        }
    }

    /**
    * 获取子节点
    * @param id 父节点id
    * @param allMenu 所有菜单列表
    * @return 每个根节点下，所有子菜单列表
    */
    public List<DeviceGroupTreeListDTO> getChild(Long id, List<DeviceGroupTreeListDTO> allMenu){
        //子菜单
        List<DeviceGroupTreeListDTO> childList = new ArrayList<DeviceGroupTreeListDTO>();
        for (DeviceGroupTreeListDTO nav : allMenu) {
            /**
             * 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
             * 相等说明：为该根节点的子节点。
             */
            if(nav.getPid() != null && (id.toString()).equals(nav.getPid())){
                childList.add(nav);
            }
        }
        //递归
        for (DeviceGroupTreeListDTO nav : childList) {
            nav.setChildren(getChild(nav.getDeviceGroupId(), allMenu));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if(childList.size() == 0){
            return new ArrayList<DeviceGroupTreeListDTO>();
        }
        return childList;
    }

    /**
     * 移动终端到分组
     * @param groupCode
     * @param deviceInfoIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/moveDeviceGroup")
    public Object moveDeviceGroup(String groupCode, String deviceInfoIds, HttpServletRequest request) {
        //获取用户信息
        JSONObject user = null;
        try {
            user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
        } catch (ServiceException e) {
            e.printStackTrace();
            logger.error("DeviceGroupController moveDeviceGroup 移动终端到分组失败：" + e.getMessage());
            return new ControllerException(e.getMessage());
        }
        if(user == null) {
            return new ControllerException("用户名为空，请联系管理员");
        }
        if(StringUtils.isBlank(groupCode) || StringUtils.isBlank(deviceInfoIds)) {
            return new ControllerException(ClientConstant.MSG_PARAM_ERROR);
        }
        try {
            deviceGroupService.moveDeviceGroup(groupCode, deviceInfoIds, user, request);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("DeviceGroupController moveDeviceGroup 移动终端到分组失败：" + e.getMessage());
            return new ControllerException("移动终端到分组失败");
        }
        return "";
    }
}
